package com.edu.servlet;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.edu.bean.Carinfo;
import com.edu.bean.News;
import com.edu.service.CarinfoService;
import com.edu.service.NewsService;
import com.edu.service.impl.CarinfoServiceImpl;
import com.edu.service.impl.NewsServiceImpl;
@WebServlet("/addNews.do")
@MultipartConfig
public class AddNewsServlet extends HttpServlet{
		@Override
		protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			req.setCharacterEncoding("UTF-8");
			NewsService ns = new NewsServiceImpl();
			String title = req.getParameter("title");
			String content = req.getParameter("content");
			String publishDate = req.getParameter("publishDate");
			String author = req.getParameter("author");
			DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
			Date newsdate = null;
			try {
				newsdate = dft.parse(publishDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			News news = new News(title,content,newsdate,author);
			Part part = req.getPart("imageUrl");
			String savePath="";
			if(part.getSize()>0 ) {
				if(part.getSize() <=1024*1024 || part.getContentType().contains("image")) {
					//生成一个独一无二的文件名.UUID，用户名_时间戳_原始文件名
					String saveName = title+"_"+System.currentTimeMillis()+part.getSubmittedFileName();
					//把文件存储到服务器的headImg路径下（真实路径）
					savePath = "c:/PhaetonCommunityImg/favoriteCar/"+saveName;
					//访问路径存在数据库，取出来之后直接拼字img下面的src的路径下
					String visitPath = "/PhaetonCommunity/favoriteCar/"+saveName;
					//用户上传的文件需要复制到真实保存路径
					part.write(savePath);
					news.setImageUrl(visitPath);
				}else {
					req.setAttribute("carimgMsg","图片必须小于1m");
					return;
				}
				
			}
	    	int result = ns.addNews(news);
	    	if(result == -1){
	    		//添加失败时，应该把上面保存在服务器里的图片删掉
	    		File file = new File(savePath);
	    		if(file.exists()) {
	    			file.delete();
	    		}
	    	} 
		}
}
